﻿using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;

namespace PssFramework
{
    namespace PSServer
    {
        class SubscriberService
        {
               static EventHandler OnServerEvent;
            public void StartSubscriberService(EventHandler OnServerEvent)
            {
                OnServerEvent.Invoke(null, new ServerEventArgs("Starting Subscribe service"));
                SubscriberService.OnServerEvent=OnServerEvent;
                Thread th = new Thread(new ThreadStart(HostSubscriberService));
                th.IsBackground = true;
                th.Start();
            }

            private void HostSubscriberService()
            {
                try
                {
                    IPAddress ipV4 = IPAddress.Parse(Config.getInstance().HostIp);
                    IPEndPoint localEP = new IPEndPoint(ipV4, Config.getInstance().SubscribePort);
                    Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    server.Bind(localEP);


                    StartListening(server);
                }
                catch(Exception exc)
                {
                    string str = exc.ToString();

                }

            }
         
            private static void StartListening(Socket server)
            {
                OnServerEvent.Invoke(null, new ServerEventArgs("Sub serv start listening"));
                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                int recv = 0;
                byte[] data = null;
                while (true)
                {

                    recv = 0;
                    data = new byte[1024];
                    recv = server.ReceiveFrom(data, ref remoteEP);
                    PssFramework.EPPSCommands Cmd = (PssFramework.EPPSCommands)Utils.getValue(data,0);
                    int Topic = Utils.getValue(data, 4);
                    switch (Cmd)
                    {
                        case PssFramework.EPPSCommands.SUBSCRIBE:
                            {
                                OnServerEvent.Invoke(null, new ServerEventArgs("SubscribeCommand"));
                                Filter.AddSubscriber(Topic, remoteEP);
                            }
                            break;
                        case PssFramework.EPPSCommands.UNSUBSCRIBE:
                            {
                                OnServerEvent.Invoke(null, new ServerEventArgs("UnSbscribeCommand"));
                                Filter.RemoveSubscriber(Topic, remoteEP);
                            }
                            break;
                    }
                }
            }
        }
    }
}